import {Injectable} from '@angular/core';
import * as CryptoJS from 'crypto-js';
import * as moment from 'moment';
import {KeyAndSign} from '../common/key-and-sign.enum';
import {NavController, ToastController} from '@ionic/angular';

@Injectable({
  providedIn: 'root'
})
export class UtilService {

  constructor(public navCtrl: NavController,
              public toastCtrl: ToastController
  ) {
  }

  // 依据参数计算_s参数值
  get_s(params: any): string {
    // 获取所有参数KEY值数组并排序
    const keyList: string[] = Object.keys(params);
    if (keyList.length > 0) {
      keyList.sort();
      // 转换为KEY=VALUE的字符串形式并使用&符连接
      const keyAndValStr = keyList.map((key) => {
        return key + '=' + params[key];
      }).join('&');
      // 进行MD5加密
      return CryptoJS.MD5(keyAndValStr + KeyAndSign._S_KEY).toString();
    }
    return '';
  }

  // 传输加密
  transmissionEncrypt(id, sign): string {
    // 将id、action标示、当前时间利用des加密
    const des = this.encryptByDES(id + ',' + sign + ',' + moment().format('YYYY-MM-DD HH:mm:ss'), KeyAndSign.DES_KEY);
    // 将加密得到的des利用MD5再次加密
    const md5 = CryptoJS.MD5(des + KeyAndSign.DES_KEY).toString();
    // 将得到的des和MD5密文拼接处理
    return des + md5.substring(0, 8);
  }

  // DES加密
  encryptByDES(message, key): string {
    const keyHex = CryptoJS.enc.Utf8.parse(key);
    const encrypted = CryptoJS.DES.encrypt(message.toString(), keyHex, {
      mode: CryptoJS.mode.ECB,
      padding: CryptoJS.pad.Pkcs7
    });
    return encrypted.ciphertext.toString().toUpperCase();
  }

  // DES解密
  decryptByDES(ciphertext, key): string {
    const keyHex = CryptoJS.enc.Utf8.parse(key);
    const decrypted = CryptoJS.DES.decrypt({
      ciphertext: CryptoJS.enc.Hex.parse(ciphertext)
    }, keyHex, {
      mode: CryptoJS.mode.ECB,
      padding: CryptoJS.pad.Pkcs7
    });
    const result_value = decrypted.toString(CryptoJS.enc.Utf8);
    return result_value;
  }

}
